const util = require("../utils/connection");
const Table = require("../utils/table");
const TableUtil = new Table(
  "address",
  ["ip", "city", "page_view", "create_time", "update_time"],
  {
    updateFilterField: ["create_time"]
  }
);
const $date = require("../utils/date");

module.exports = {
  /**
   * 查询地址
   * @param {Object} query 拥有ip/city/pageView/createTime/updateTime属性
   * @return {Promise<void>}
   */
  select: function(query) {
    return new Promise(async resolve => {
      let sql =
        "select id, ip, city, page_view, create_time, update_time from address where 1 = 1 ";
      Object.keys(query).forEach(field => {
        if (query[field]) {
          sql +=
            field === "ip"
              ? `and ip = '${query[field]}'`
              : `and ${field} = '${query[field]}'`;
        }
      });
      const connection = await util.getConnection();
      connection.query(sql, function(error, results) {
        connection.release();
        if (error) throw error;
        const data = results.length > 1 ? results : results[0] || {};
        resolve({ data });
      });
    });
  },
  /**
   * 新增/修改地址
   * @param obj 需要新增/修改的数据对象
   * @return {Promise<*>}
   */
  insertOrUpdate: async function(obj) {
    const { data } = await this.select({ ip: obj.ip });
    const now = $date.format(new Date());
    obj["id"] = data["id"];
    obj["update_time"] = now;
    if (obj.id) {
      obj["page_view"] = ++data["page_view"];
    } else {
      obj["create_time"] = now;
      obj["page_view"] = 1;
    }
    return TableUtil.insertOrUpdate(obj);
  }
};
